import showToast from "../../../utils/toast";
wx.cloud.init({
  env: 'sleep-sign-0g9xr6lm95e07431'
})
const db = wx.cloud.database()
const user_chaoxing = db.collection('user_chaoxing')
async function getConfigByUsername(username: string): Promise<DBResult<UserChaoxing>> {
  // 没有记录,会抛出异常
  console.log(username)
  return user_chaoxing.where({
    _id: username,
  }).get() as unknown as Promise<DBResult<UserChaoxing>>
}

async function getConfigByParma(_param: Partial<UserChaoxing>): Promise<DBResult<UserChaoxing>> {
  // 没有记录,会抛出异常
  const param = Object.assign(_param)
  let key: keyof Partial<UserChaoxing>
  for (key in _param){
    if (typeof _param[key] == 'undefined'){
      delete param[key]
    }
  }
  return user_chaoxing.where({
  ...param
  }).get() as unknown as Promise<DBResult<UserChaoxing>>
}

async function getConfigAll(): Promise<DBResult<UserChaoxing>> {
  // 没有记录,会抛出异常
  return user_chaoxing.where({}).get() as unknown as Promise<DBResult<UserChaoxing>>
}

async function setOrUpdateConfigByUsername(data: UserChaoxing) {
  try {
    await getConfigByUsername(data._id);
    await wx.cloud.callFunction({
      name: 'setOrupdateConfig',
      data,
    })
  }
  catch (ignored) {
    showToast({ title: "更新数据失败", "icon": 'error' })
  }
}


export default { getConfigByUsername, setOrUpdateConfigByUsername, getConfigAll,getConfigByParma }